package com.bangcommunity.bbframe.fdfs.connection;

import org.apache.commons.pool2.KeyedPooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;

import com.bangcommunity.bbframe.fdfs.config.FdfsClientConfig;

import java.io.IOException;

/**
 * @author tanghc
 * @date 18/6/22
 */
public class TrackerConnectionFactory implements KeyedPooledObjectFactory<String, TrackerConnection> {

    private FdfsClientConfig fastdfsClientConfig;

    public TrackerConnectionFactory() {
        this(null);
    }

    public TrackerConnectionFactory(FdfsClientConfig fastdfsClientConfig) {
        super();
        this.fastdfsClientConfig = fastdfsClientConfig;
    }

    public GenericKeyedObjectPoolConfig getClientPoolConfig() {
        return fastdfsClientConfig.getTrackerClientPoolConfig();
    }

    @Override
    public PooledObject<TrackerConnection> makeObject(String key) throws Exception {
        TrackerConnection trackerConnection = new TrackerConnectionImpl(key);
        return new DefaultPooledObject<>(trackerConnection);
    }

    @Override
    public void destroyObject(String key, PooledObject<TrackerConnection> p) throws Exception {
        TrackerConnection trackerConnection = p.getObject();
        trackerConnection.close();
    }

    @Override
    public boolean validateObject(String key, PooledObject<TrackerConnection> p) {
        TrackerConnection trackerConnection = p.getObject();
        try {
            return !trackerConnection.isClosed();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void activateObject(String key, PooledObject<TrackerConnection> p) throws Exception {

    }

    @Override
    public void passivateObject(String key, PooledObject<TrackerConnection> p) throws Exception {

    }

    public FdfsClientConfig getFastdfsClientConfig() {
        return fastdfsClientConfig;
    }

    public void setFastdfsClientConfig(FdfsClientConfig fastdfsClientConfig) {
        this.fastdfsClientConfig = fastdfsClientConfig;
    }
}
